<template>
  <el-form :label-width="labelWidth" ref="formRef" :model="formData">
    <template v-for="item in formItems" :key="item.label">
      <el-form-item
        v-if="!item.isHidden"
        :label="item.label"
        :rules="item.rules"
        :prop="item.field"
        :style="itemStyle"
      >
        <template v-if="item.type === 'input' || item.type === 'password'">
          <el-input
            v-model="formData[item.field]"
            :placeholder="item.placeholder"
            :show-password="item.type === 'password'"
            v-bind="item.otherOptions"
          />
        </template>
        <template v-else-if="item.type === 'select'">
          <el-select
            v-model="formData[item.field]"
            :placeholder="item.placeholder"
            style="width: 100%"
            v-bind="item.otherOptions"
          >
            <el-option
              v-for="option in item.options"
              :key="option.value"
              :label="option.title"
              :value="option.value"
            >
              {{ option.title }}
            </el-option>
          </el-select>
        </template>
        <template
          v-else-if="item.type === 'datepicker' || item.type === 'date'"
        >
          <el-date-picker
            v-model="formData[item.field]"
            style="width: 100%"
            v-bind="item.otherOptions"
          ></el-date-picker>
        </template>
      </el-form-item>
    </template>
    <div class="haandle-btns">
      <el-button @click="resetForm">重置</el-button>
      <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
    </div>
  </el-form>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import type { FormInstance } from "element-plus";
interface Props {
  itemStyle?: any;
  labelWidth?: string;
  submitFormConfig: any;
}
const props = withDefaults(defineProps<Props>(), {
  submitFormConfig: () => ({}),
  labelWidth: "80px",
  itemStyle: () => ({ padding: "10px" }),
});
const formRef = ref<FormInstance>();
const formItems = props.submitFormConfig?.formItems ?? [];
const emit = defineEmits<{
  (e: "queryBtnClick", newFormData: any): void;
}>();
const formOriginData: any = {};
for (const item of formItems) {
  formOriginData[item.field] = item.default;
}
const formData = ref(formOriginData);

const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
};

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      emit("queryBtnClick", formData.value);
    } else {
      console.log("error submit!");
    }
  });
};
const setForm = (data: any) => {
  console.log(formData.value);
  for (const item in formData.value) {
    formData.value[item] = data[item];
  }
};
defineExpose({ setForm, resetForm });
</script>
<style scoped>
.haandle-btns {
  text-align: right;
}
</style>
